package com.erpx.api;

import com.erpx.utils.StringUtils;
import com.erpx.utils.WebUtils;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 奇门自定义接口
 */
public class QimenDemo {

    /**
     * 旺店通使用的appkey
     */
    public static String wdtAppKey = "appkey_leyan_test";

    /**
     * 旺店通使用的租户sid 用来标识查询哪个客户的数据
     */
    public static String wdtSid = "qatest";

    /**
     * 我方奇门应用的appkey  阿里奇门中心给到的appkey
     */
    public static String APP_KEY ="";
    /**
     * 我方奇门应用的密钥  阿里奇门中心给到的密钥
     */
    public static String APP_SECRET = "";

    /**
     * 旺店通奇门应用测试环境地址
     */
    public static String wdtTestQimenUrl = "https://4edcetl6p0.api.taobao.com/router/qmtest";

    /**
     * 旺店通奇门应用测试环境地址
     */
    public static String wdtProdQimenUrl = "https://4edcetl6p0.api.taobao.com/router/qm";

    /**
     * 连接超时时间 ms
     */
    public static int connectTimeout = 10000;

    public static int readTimeout = 5000;

    public static void main(String[] args) {
        executeQimenQueryTrade();
    }

    /**
     * 奇门查询订单
     */
    public static void executeQimenQueryTrade(){
        Map<String, String> params = new HashMap<>();
        params.put("method","wdt.trade.query");
        params.put("page_no","0");
        params.put("page_size","100");
        params.put("start_time","2024-11-04 08:00:00");
        params.put("end_time","2024-11-04 08:50:00");
        try {
            String s = executeQimen(wdtTestQimenUrl, params);
            System.out.println(s);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static String executeQimen(String relativeUrl, Map<String, String> params) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
        params.put("appkey", wdtAppKey);
        params.put("sid", wdtSid);
        params.put("app_key",APP_KEY);
        params.put("timestamp", sdf.format(new Date()));
        params.put("format", "json");
        params.put("sign_method", "md5");
        params.put("target_app_key", "21363512");
        params.put("v", "2.0");
        params.put("sign", signTopRequest(params, APP_SECRET));


        return WebUtils.doPost(relativeUrl, params, "UTF-8", connectTimeout, readTimeout, null);

    }

    public static String signTopRequest(Map<String, String> params, String secret)
        throws IOException {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet()
            .toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        query.append(secret);
        for (String key : keys) {
            if ("sign".equals(key)) {
                continue;
            }
            String value = params.get(key);
            if (StringUtils.areNotEmpty(key, value)) {
                query.append(key)
                    .append(value);
            }
        }

        // 第三步：使用MD5/HMAC加密
        byte[] bytes;
        query.append(secret);
        bytes = encryptMD5(query.toString());

        // 第四步：把二进制转化为大写的十六进制(正确签名应该为32大写字符串，此方法需要时使用)
        return byte2hex(bytes);
    }

    public static byte[] encryptMD5(String data) throws IOException {
        return encryptMD5(data.getBytes("utf-8"));
    }

    public static byte[] encryptMD5(byte[] data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data);
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse.toString());
        }
        return bytes;
    }

    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }
}
